package com.emm.yixun.mobile.ui.web.helper

import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.webkit.WebView
import com.emm.yixun.mobile.application.EmmApplication
import com.emm.yixun.mobile.ui.FromListActivity
import com.emm.yixun.mobile.ui.customer.FollowUpActivity
import com.emm.yixun.mobile.ui.web.bean.CustomerDetail
import com.emm.yixun.mobile.ui.web.KeyConstant
import com.emm.yixun.mobile.ui.web.WebActivity
import com.emm.yixun.utils.ToastUtils
import com.google.gson.Gson
import java.net.URLDecoder


class WebHelper(val activity: WebActivity) {

    fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
        when {
            url.startsWith(SCHEMA_NATIVE) -> {
                val webAction = handleAction(url)
                when (webAction.first) {
                    ACTION_GO_BACK -> activity.onBackPressed()
                    ACTION_RECRUIT_LIST,
                    ACTION_SUBSCRIPTION_LIST,
                    ACTION_SIGNING_LIST -> jump2FromListActivity(webAction.first, webAction.second)
                    ACTION_CALL_CUSTOMER -> callCustomer(webAction.second)
                    ACTION_SEND_SMS_CUSTOMER -> sendSMS(webAction.second)
                    ACTION_WRITE_FOLLOW -> jump2WriteFollow(webAction.second)
                    else -> Log.d("WebHelper", "未处理的请求")
                }
            }
            else -> webView.loadUrl(url)
        }

        return true
    }

    fun doAfterGetCustomerDetail(webView: WebView, func: (detail: CustomerDetail) -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:window.getUserInfo()") { value ->
                val detail = Gson().fromJson(value, CustomerDetail::class.java)
                func(detail)
            }
        }
    }

    private fun handleAction(url: String): Pair<String, Map<String, String>> {
        var action = ""
        val params = mutableMapOf<String, String>()

        val handleParams = fun(s: String) {
            s.split("&")
                .forEach {
                    val paramPair = it.split("=")

                    if (paramPair.size == 2) {
                        val key = paramPair[0]
                        // 接收到编码后的字符串 需要解码成实际字符串
                        val value = URLDecoder.decode(paramPair[1], "utf8")
                        params[key] = value
                    }
                }
        }

        url.replaceFirst(SCHEMA_NATIVE, "")
            .split("?")
            .forEachIndexed { index, s ->
                if (index == 0) {
                    action = s
                } else if (index == 1) {
                    handleParams(s)
                }
            }

        return Pair(action, params)
    }

    private fun jump2FromListActivity(action: String, params: Map<String, String>) {
        val customerId = params[KeyConstant.KEY_CUSTOMER_ID] ?: return showParamError()
        val userName = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_NAME])
        val userTel = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_TEL])

        val type = when (action) {
            ACTION_RECRUIT_LIST -> 1
            ACTION_SUBSCRIPTION_LIST -> 2
            ACTION_SIGNING_LIST -> 3
            else -> 1
        }

        val intent = Intent(activity, FromListActivity::class.java)
        intent.putExtra("Dotype", type)
        intent.putExtra("USERDATA", userName)
        intent.putExtra("USERTEL", userTel)
        intent.putExtra("customerId", customerId)
        activity.startActivity(intent)
    }

    private fun jump2WriteFollow(params: Map<String, String>) {
        val customerId = params[KeyConstant.KEY_CUSTOMER_ID] ?: return showParamError()

        val customerSex = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_SEX])
        val intentionLevel = selfOrEmpty(params[KeyConstant.KEY_INTENTION_LEVEL])
        val customerStatus = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_STATUS])
        val customerOrigin = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_ORIGIN])
        val customerStar = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_STAR])
        val customerName = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_NAME])
        val customerPhone = selfOrEmpty(params[KeyConstant.KEY_CUSTOMER_TEL])

        val intent = Intent(activity, FollowUpActivity::class.java)
        intent.putExtra("customerId", customerId)
        intent.putExtra("SEX", customerSex)
        intent.putExtra("NUMBER", intentionLevel)
        intent.putExtra("CUSTOMERSTATUS", customerStatus)
        intent.putExtra("CUSTOMERORIGIN", customerOrigin)
        intent.putExtra("STAR", customerStar)
        intent.putExtra("NAME", customerName)
        intent.putExtra("TEL", customerPhone)
        activity.startActivity(intent)
    }

    private fun callCustomer(params: Map<String, String>) {
        val tel = params[KeyConstant.KEY_CUSTOMER_TEL] ?: return showParamError()
        val customerId = params[KeyConstant.KEY_CUSTOMER_ID] ?: return showParamError()
        EmmApplication.callPhone(tel, customerId)
    }

    private fun sendSMS(params: Map<String, String>) {
        val tel = params[KeyConstant.KEY_CUSTOMER_TEL] ?: return showParamError()
        EmmApplication.sendMMS(listOf(tel))
    }

    private fun showParamError() {
        ToastUtils.showToast("参数错误")
    }

    private fun selfOrEmpty(param: String?): String {
        return if (isNull(param)) {
            ""
        } else {
            param!!
        }
    }

    private fun isNull(str: String?): Boolean {
        return null == str || TextUtils.isEmpty(str) || "" == str || "null" == str || "undefined" == str
    }

    companion object {
        private const val SCHEMA_NATIVE = "native://"

        private const val ACTION_RECRUIT_LIST = "recruit_list"
        private const val ACTION_SUBSCRIPTION_LIST = "subscription_list"
        private const val ACTION_SIGNING_LIST = "signing_list"
        private const val ACTION_CALL_CUSTOMER = "call_customer"
        private const val ACTION_SEND_SMS_CUSTOMER = "send_sms_customer"
        private const val ACTION_WRITE_FOLLOW = "write_follow"
        private const val ACTION_GO_BACK = "go_back"

        const val CUSTOMER_DETAIL = "customer_detail"
    }

}